//
//  TVCommodityDetailCell.swift
//  iPhone
//
//  Created by Toj on 8/10/22.
//

import UIKit

protocol TVCommodityDetailCellDelegate: NSObjectProtocol {
    func commodityDetailCell(_ view: TVCommodityDetailCell, didSelected commodity: TVCommodityCellModel)
    
    func commodityDetailCell(_ view: TVCommodityDetailCell, didTapAmount index: Int, amount: Int)
}

// MARK: - 懒加载(属性), 变量, 初始化init
class TVCommodityDetailCell: UICollectionViewCell {
    
    weak var delegate: TVCommodityDetailCellDelegate?
    
    var cellModel: TVProductCellModel? { didSet {
        reloadData()
    }}
    
    private func reloadData() {
        guard let commodity = cellModel?.selectedCommodity else { return }
        giftTipsView.cellModel = commodity
        amountView.amounts = commodity.numbers
        amountView.selectedIndex = commodity.selectedNumberIndex
        setupRemakeLayoutSubviews()
        collectionView.reloadData()
        
        guard cellModel?.isLoaded == false else { return }
        cellModel?.isLoaded = true
        
        let selectedIndex = cellModel?.selectedIndex ?? -1
        guard selectedIndex >= 0 else { return }
        collectionView.layoutIfNeeded()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            self.rightShadowHidden()
            let indexPath = IndexPath(row: selectedIndex, section: 0)
            self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupMakeAddSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        setupMakeLayoutSubviews()
    }
    
    private lazy var titleLable: UILabel = {
        let view = UILabel()
        view.text = "dvb_recharge_link_recharge".localized()
        view.textColor = "#333333".to_color
        view.font = UIFont.boldSystemFont(ofSize: 16)
        return view
    }()
    
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 8
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: 104, height: 112)

        let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
        //view.bounces = false
        view.scrollsToTop = true
        //view.alwaysBounceVertical = true
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.contentInsetAdjustmentBehavior = .never
        view.backgroundColor = .white
        view.contentInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        view.register(TVCommodityDetailSpecCell.cell_class, forCellWithReuseIdentifier: TVCommodityDetailSpecCell.cell_identifier)
        view.dataSource = self
        view.delegate = self
        return view
    }()
    
    private lazy var giftTipsView: TVCommodityGiftTipsView = {
        let view = TVCommodityGiftTipsView()
        return view
    }()
    
    private lazy var amountTitleLable: UILabel = {
        let view = UILabel()
        view.text = "dvb_recharge_amount".localized()
        view.textColor = "#424242".to_color
        view.font = UIFont.boldSystemFont(ofSize: 14)
        return view
    }()
    
    private lazy var amountView: TVAmountView = {
        let view = TVAmountView()
        view.delegate = self
        view.normalGradationColors = ["#FFEEC0".to_color.st_alpha(0.22).cgColor, "#E8CD8C".to_color.st_alpha(0.3).cgColor]
        view.selectedGradationColors = ["#F5DB9D".to_color.cgColor, "#E8CD8C".to_color.cgColor]
        return view
    }()
    
    private lazy var leftArrowImageView: UIImageView = {
        let view = UIImageView()
        view.image = "com_commodity_arrow_left".to_image
        return view
    }()
    private lazy var leftShadowImageView: UIImageView = {
        let view = UIImageView()
        view.isHidden = true
        view.image = "com_commodity_shadow_left".to_image
        return view
    }()
    private lazy var rightArrowImageView: UIImageView = {
        let view = UIImageView()
        view.image = "com_commodity_arrow_right".to_image
        return view
    }()
    private lazy var rightShadowImageView: UIImageView = {
        let view = UIImageView()
        view.isHidden = true
        view.image = "com_commodity_shadow_right".to_image
        return view
    }()
    
    private func rightShadowHidden() {
        let rightIsHidden = (collectionView.contentSize.width + 16) < CGFloat.sr_width
        rightShadowImageView.isHidden = rightIsHidden
    }
}

// MARK: - 代理事件 UICollectionViewDataSource
extension TVCommodityDetailCell: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cellModel?.commodities.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TVCommodityDetailSpecCell.cell_identifier, for: indexPath, TVCommodityDetailSpecCell.self)
        cell.cellModel = cellModel?.commodities[indexPath.row]
        return cell
    }
}

// MARK: - 代理事件 UICollectionViewDataSource
extension TVCommodityDetailCell: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let cell = collectionView.cellForItem(at: indexPath) as? TVCommodityDetailSpecCell, let commodity = cell.cellModel else { return }
        if commodity == cellModel?.selectedCommodity { return }
        delegate?.commodityDetailCell(self, didSelected: commodity)
        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsetX = scrollView.contentOffset.x
        if offsetX < 10 {
            if leftShadowImageView.isHidden { return }
            leftShadowImageView.isHidden = true
            rightShadowHidden()
            return
        }
        
        if leftShadowImageView.isHidden {
            leftShadowImageView.isHidden = false
        }
       
        if offsetX > (scrollView.contentSize.width - CGFloat.sr_width + 6) {
            if rightShadowImageView.isHidden { return }
            rightShadowImageView.isHidden = true
            return
        }
        
        if rightShadowImageView.isHidden {
            rightShadowImageView.isHidden = false
        }
    }
}

// MARK: - TVAmountViewDelegate
extension TVCommodityDetailCell: TVAmountViewDelegate {
    func amountView(_ view: TVAmountView, didTapSegment index: Int, amount: Int) {
        delegate?.commodityDetailCell(self, didTapAmount: index, amount: amount)
    }
}

// MARK: - 初始化
extension TVCommodityDetailCell {
    
    private func setupMakeAddSubviews() {
        
        contentView.addSubview(titleLable)
        contentView.addSubview(collectionView)
        contentView.addSubview(giftTipsView)
        contentView.addSubview(amountTitleLable)
        contentView.addSubview(amountView)
        
        contentView.addSubview(leftShadowImageView)
        leftShadowImageView.addSubview(leftArrowImageView)
        contentView.addSubview(rightShadowImageView)
        rightShadowImageView.addSubview(rightArrowImageView)
    }
    
    private func setupMakeLayoutSubviews() {
        
        titleLable.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(4)
            make.right.equalTo(contentView.snp.right).offset(-16)
            make.height.equalTo(40)
        }
        
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(titleLable.snp.bottom)
            make.left.right.equalTo(contentView)
            make.height.equalTo(112)
        }
        
        giftTipsView.snp.makeConstraints { make in
            make.top.equalTo(collectionView.snp.bottom).offset(8)
            make.left.right.equalTo(titleLable)
            make.height.equalTo(28)
        }
        
        leftShadowImageView.snp.makeConstraints { make in
            make.top.bottom.left.equalTo(collectionView)
            make.width.equalTo(40)
        }
        
        leftArrowImageView.snp.makeConstraints { make in
            make.left.equalTo(3)
            make.centerY.equalTo(leftShadowImageView)
            make.width.equalTo(24)
            make.height.equalTo(24)
        }
        
        rightShadowImageView.snp.makeConstraints { make in
            make.top.bottom.right.equalTo(collectionView)
            make.width.equalTo(leftShadowImageView)
        }
        
        rightArrowImageView.snp.makeConstraints { make in
            make.centerY.width.height.equalTo(leftArrowImageView)
            make.right.equalTo(rightShadowImageView).inset(3)
        }
        
        setupRemakeLayoutSubviews()
    }
    
    private func setupRemakeLayoutSubviews() {
        let offset: CGFloat = giftTipsView.isHidden ? 0 : 40
        amountTitleLable.snp.remakeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(collectionView.snp.bottom).offset(offset)
            make.right.equalTo(contentView.snp.right).offset(-16)
            make.height.equalTo(40)
        }
        
        amountView.snp.remakeConstraints { make in
            make.left.equalTo(16)
            make.top.equalTo(amountTitleLable.snp.bottom)
            make.right.equalTo(contentView.snp.right).offset(-16)
            make.bottom.equalTo(contentView)
        }
    }
}
